<template>
    <video ref="video" class="video" :src="url" controls :style="{ width, height }"></video>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import Hls from 'hls.js'

const props = defineProps({
    url: {
        type: String,
        required: true,
    },
    width: {
        type: String,
        default: '0px',
    },
    height: {
        type: String,
        default: '0px',
    },
})

const video = ref(null)

onMounted(() => {
    const hls = new Hls()
    if (Hls.isSupported()) {
        const url = props.url

        if (isHLS(url)) {
            // console.log('Using HLS for:', url)
            hls.loadSource(url)
            hls.attachMedia(video.value)
            setupHlsListeners(hls)
        } else {
            // 如果不是 HLS 流，则直接设置 src 属性
            video.value.src = url
            video.value.onloadedmetadata = function (e) {
                // video.value.play()
            }
        }
    } else {
        console.error('HLS 不受支持')
    }
})

// 辅助函数，判断是否为 HLS 流
const isHLS = (src) => {
    return src.endsWith('.m3u8')
}

// 设置 HLS 事件监听器
const setupHlsListeners = (hls) => {
    hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
        // console.log('Manifest parsed:', data)
        // video.value.play()
    })

    hls.on(Hls.Events.ERROR, function (event, data) {
        // console.error('HLS error:', data)
        if (data.fatal) {
            switch (data.type) {
                case Hls.ErrorTypes.NETWORK_ERROR:
                    hls.startLoad()
                    break
                case Hls.ErrorTypes.MEDIA_ERROR:
                    hls.recoverMediaError()
                    break
                default:
                    hls.destroy()
                    break
            }
        }
    })

    hls.on(Hls.Events.LEVEL_PTS_UPDATED, function (event, data) {
        // console.log('Level PTS updated:', data)
    })

    hls.on(Hls.Events.BUFFER_APPENDED, function (event, data) {
        // console.log('Buffer appended:', data)
    })

    hls.on(Hls.Events.BUFFER_EOS, function (event, data) {
        // console.log('Buffer EOS:', data)
    })
}
</script>

<style lang="scss" scoped>
.video {
    border-radius: 4px;
}
</style>
